import com.xfactorstudio.xml.xpath.*;
import timber.ui.TableDataSourceInterface;

/**
	Wrapper for Xfactor stuido's XPath class so it can be used as a TableDataSource.

	@author Chandler McWilliams
	@version 2005-05-01
*/

class timber.data.XPathData implements TableDataSourceInterface
{
	private var items;
	private var root;
	private var thexml:XML;

	
// ===========================================================
// - CONSTRUCTOR
// ===========================================================
	public function XPathData(theurl, thecallback) {		
		// if the url arg is false, don't load anything
		if (!theurl) return;
		
		// init items and root
		items = new Array();
		root = '/';

		thexml = new XML();
		thexml.ignoreWhite = true;
		var self = this;
		thexml.onLoad = function(ok) {
		   if (ok) {
		  		thecallback(ok);
			}
		}
		thexml.load(theurl.toString());
	}

// ===========================================================
// - ACCESORS
// ===========================================================	
	public function setData(newxml) { thexml = newxml;}
	public function setRoot(val) { root = val; }
	


// ===========================================================
// - HANDY ACCESORS
// ===========================================================
	// return the node at num
	public function getNode(num) {
		return selectSingleNode(root+'['+num+']');
	}

	public function selectNodes(path) {
		return com.xfactorstudio.xml.xpath.XPath.selectNodes(thexml, path);
	}

	public function selectSingleNode(path) {
		return com.xfactorstudio.xml.xpath.XPath.selectNodes(thexml, path)[0];
	}



// ===========================================================
// - MISC
// ===========================================================
	// returns a new XPathData object of the result of a query
	public function getFragment(query) {
		var frag = new XPathData(false);
		var arr = selectNodes(query);
		frag.setData(new XML(arr[0]));
		return frag;
	}



// ===========================================================
// - FOR THE TableDataSourceInterface
// ===========================================================
	public function numberOfRowsInTable(table) {
		// the compiler is so retarded.
		return selectNodes(root).length;
	}
	
	public function valueForTableAtRowColumn(table, row, column) {
		// first assume its a node
		var query = root+'['+(row+1)+']/'+column;
		var n = selectSingleNode(query);
		
		// if it isn't try an attribute
		if (!n) {
			query = root+'['+(row+1)+']/@'+column;
			n = selectSingleNode(query);
			return n.nodeValue;
		}
		return n.firstChild.nodeValue;
	}
	
}